import { ConditionBase } from "../condition/ConditionBase";
import { EffectBase } from "../effect/EffectBase";
import { BattleRole } from "../role/BattleRole";
import { ITriggerResult } from "./const/ITriggerResult";
import { ITriggerData } from "./const/ITriggerData";
import { ConditionCreator } from "../condition/ConditionCreator";
import { TriggerType } from "./const/TriggerType";
import { EffectCreator } from "../effect/EffectCreator";

/**
 * 触发器基类
 */
export class TriggerBase {
    gid: number;//唯一id
    triggerType: TriggerType;//触发器类型
    conditions: ConditionBase[];//条件
    actions: EffectBase[];//行动
    cooldown: number;//冷却
    currentCooldonw: number;//剩余冷却回合
    maxActivations: number;//最大触发次数（-1表示无限）
    activationCount: number;//已触发次数

    constructor(data: ITriggerData) {
        this.triggerType = data.triggerType;
        this.conditions = [];
        this.actions = []
        if (data.conditionDatas) {
            for (let one of data.conditionDatas) {
                let cond = ConditionCreator.createCond(one);
                this.conditions.push(cond)
            }
        }
        if (data.effects) {
            for (let effData of data.effects) {
                let eff = EffectCreator.create(effData);
                this.actions.push(eff)
            }
        }
        this.activationCount = 0
        this.maxActivations = data.activationCount;
    }

    /**检查条件 */
    checkConditions(args: any) {
        if (this.currentCooldonw > 0) return false;
        if (this.maxActivations > 0 && this.activationCount > this.maxActivations) return false;

        for (let condition of this.conditions) {
            if (!condition.isPass(args)) {
                return false;
            }
        }
        return true;
    }

    /**执行触发动作 */
    executeActions(args: { caster: BattleRole, target: BattleRole, results: ITriggerResult[] }) {
        if (!this.checkConditions(args)) return;

        for (let action of this.actions) {
            action.excute(args)
        }

        this.currentCooldonw = this.cooldown;
        this.activationCount++;
    }

    isFinish() {
        return this.activationCount >= this.maxActivations;
    }
}